public without sharing class AssignmentReportController {
   

    public Boolean isErr {get;set;}


  public User u ;//当前用户

  public String accJson {get;set;}//可以查看的客户的pk ;

  public String sql {get;private set;} ///有权限的sql ;

  public String countSql {get;private set;}

    public String  CompanyJson {get;private set;}

    public Boolean isSeeAll {get;private set;}

    public String accountSql {get;private set;}//获取客户的sql;

    public  String  company ;

    public String whereStr {get;set;}

    public Integer accCount {get;private set;}

    public Set<String> accset ;

    public String secret {get;private set;}

    public Boolean salerRight;

    public Boolean isSubRight;

    public String accpk {get ;set;}

    public String equipJson {get; private set;}

    public Boolean isAreaRight;

    public AssignmentReportController() {
        accJson = '{}';
        accset = new Set<String>();
        whereStr = '';
    }

    public void equipInit(){
        accpk = System.currentPageReference().getParameters().get('id');
        getEquipMent();

    }


    public void init(){
      u  = [select Id,Name, Profile.Name,SubCompany__c,UserDepartment__c from User where Id=:UserInfo.getUserId()];
        secret = EncodingUtil.urlEncode(EncodingUtil.base64Encode(Crypto.generateDigest('MD5',Blob.valueOf(u.Id+'secret'))), 'UTF-8');
        isSeeAll = getRight(Label.AssignmentAllRight);
        salerRight = getRight(Label.AssignmentSaleRight);
        isSubRight = getRight(Label.AssignmentSubRight);

        isAreaRight = getCompanys(u.Name) != null ;
      if(isSeeAll || salerRight || isAreaRight || isSubRight){

      }else{
        setError('没有权限查看!');
        return ;
      }
        Map<String,String >   companyMap = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false);
        company = companyMap.get(u.SubCompany__c);
      getAccounts();
    }
    public Boolean getRight(String right){
        if(right != null){
            for(String r : right.split(',',-1)){
                if(r == u.Profile.Name) return true;
                if(r == u.Name) return true;
            }
        }
        return false;
    }
    public List<String> getCompanys(String username ){
        try {
            String companys = Label.AssignmentAreaRight;

            for(String sub  : companys.split(',',-1)){

                List<String> subs = sub.split('-',-1);
                if(subs[0] == username){

                    return subs[1].split(';',-1);
                }

            }
        }catch (Exception e) {}
        
        
        return null;
        
    }
    public void getEquipMent(){
        List<Map<String,String>>  eList = new List<Map<String,String>>();

       for(TaskEquipment__c te : [select InstrumentType__c, InstrumentBrand__c, EnterWay__c , SerialNo__c ,
        InstrumentName__r.Name,Standers__r.TerminalCustomer__r.Name ,Standers__r.StartingDate__c,Standers__r.EndingDate__c,OutdoorDate__c ,
        ProductName__c,pingpai__c,Model__c
        from TaskEquipment__c where Standers__r.Account__r.NCICCode__c =:accpk or Standers__r.Account__c =:accpk ]){

             Map<String,String> e = new Map<String,String>();
            Boolean isRelated = te.InstrumentName__c == null ? false : true;

            e.put('enumber',te.SerialNo__c);
            e.put('enterway',te.EnterWay__c);
            e.put('name',isRelated ? te.InstrumentName__r.Name : te.ProductName__c);
            e.put('terminal',te.Standers__r.TerminalCustomer__r.Name );
            e.put('model',isRelated ? te.InstrumentType__c : te.Model__c);
            e.put('brand',isRelated ? te.InstrumentBrand__c : te.pingpai__c );
            e.put('coostartdate',getDate(te.Standers__r.StartingDate__c) );
            e.put('cooenddate',getDate(te.Standers__r.EndingDate__c));
            e.put('outdoordate',getDate(te.OutdoorDate__c));
            
            eList.add(e);
       }
       System.debug(eList);
       equipJson = EncodingUtil.urlEncode(JSON.serialize(eList), 'UTF-8');


    }
    private string getDate(Date d ){

        if(d == null) return '';
        return Datetime.newInstance(d.year(), d.month(), d.day()).format('yyyy-MM-dd');
    }
    public void getAccountSql(){

       // System.debug(transStr(new Set<String>(getCompanys('王林'))));

       accountSql = ' select Account__r.Name ,AccountPK__c from AssignmentReports__c  where AccountPK__c != null ';
       if(!isSeeAll) {
            if(isAreaRight){
                accountSql +=  ' and  CompanyCode__c in '+transStr(new Set<String>(getCompanys(u.Name))); 
            }else{
                accountSql += ' and  CompanyCode__c = \''+company+ '\'';
                if(!isSubRight && accset.size() == 0){
                    setError('没有数据!');
                    return;
                }

                if(!isSubRight)accountSql += ' and AccountPK__c in ' +  transStr(accset);
            }
         
       }
         if(whereStr.length() > 0){
            accountSql += whereStr;
         }
      accountSql += '   GROUP BY AccountPK__c,Account__r.Name limit 50000 ';
        System.debug(accountSql);
      Map<String ,String > accMap = new Map<String,String>();
        List<AggregateResult> accs =  Database.query(accountSql);
        accCount = accs.size();
      for(AggregateResult arg :accs){
        accMap.put(String.valueOf(arg.get('AccountPK__c')), String.valueOf(arg.get('Name')));
      }
      accJson = EncodingUtil.urlEncode(JSON.serialize(accMap), 'UTF-8'); 
    }
  
    public void setError(String message){
      isErr = true;
      ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }
    ///获取当前用户的所有客户
    ///Owner 和客户协同小组中角色为 :同客户多人负责
    public void getAccounts(){


        Map<String,String> accMap = new Map<String,String>();
      Set<Id>  salerSet = new Set<Id>();


      //1.找到所有销售员
      for(User saler: [select Id from User where ManagerId =:u.Id]){
        salerSet.add(saler.Id);
      }
      //再加上自己
      salerSet.add(u.Id);
      //1.找到所有当用户负责的客户
      for(Account acc :[select Id ,NCICCode__c ,Owner.Name,Name from Account where OwnerId In:salerSet]){
        if(acc.NCICCode__c != null )accMap.put(acc.NCICCode__c,acc.Name);
           
      }
      //2.找到协同小组中包含当前用户的客户
      for(AccountTeamMember at : [select Id ,user.Name,AccountId,Account.NCICCode__c ,Account.Name from AccountTeamMember where userId in:salerSet and teammemberrole = '销售绩效分配客户权限']){
        if(at.Account.NCICCode__c != null)accMap.put(at.Account.NCICCode__c,at.Account.Name);
      }
        accset.addAll(accMap.keySet());
      setSql(accMap.keySet());
      getAccountSql();
      //accJson = EncodingUtil.urlEncode(JSON.serialize(accMap), 'UTF-8'); 

    }
    //获取子公司对应的公司缩写
    public String getRetrunCompany(){
      Map<String ,String> comMap = new Map<String,String>();
      for(String com : Label.ShortCompanyName.split(',',-1)){
        List<String> cs = com.split('-',-1);
        if(cs != null && cs.size() > 1)comMap.put(cs[0],cs[1]);
      }

      //获取公司编码
    return comMap.get(ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(u.SubCompany__c));      
    }


    public String transStr (Set<String> nset){
      if(nset == null || nset.size()== 0)return '()';
      String s = JSON.serialize(nset);
      s = s.replaceAll('"','\'');
    s = s.replace('[','(');
    s = s.replace(']',')');
    System.debug(s);
    return s;

    }
    public void setSql(Set<String> nset){

         String year = String.valueOf(System.now().year());
     sql = ' select Account__r.Name ,AccountPK__c , Brand__c , Category1__c , Category2__c ,Year__c ,Type__c , ';
     sql += ' SaleAmount__c , CurrentSaleAmount__c ,CurrentAssignAmount__c ,AssignAmount__c ';
     sql += ' from AssignmentReports__c where AccountPK__c != null and Year__c <=\''+year+'\' ';
        if(isSeeAll)return;
        if(isAreaRight) {
            sql += ' and  CompanyCode__c in '+transStr(new Set<String>(getCompanys(u.Name))); 
            return;
        }
        ///归口公司
    sql += '  and CompanyCode__c = \'' +company +'\'';

        if(isSubRight) return;
    sql += ' and  AccountPK__c in ' + transStr(nset);


    }
    public void setNil(){
      accJson ='';
        equipJson = '';
        accpk = '';

    }
}